(function($){	
	
	function IPhoneSwitch(selector, start_state){
		
		var _this = this;
		
		this.wrapper = $(selector);
		this.state = start_state == 'on' ? start_state : 'off';
				
		// make the container
		this.wrapper.html([
		    '<div class="iphone-switch-container">',
                '<div class="iphone-switch" style="background-position:{0}px" ></div>',
            '</div>'
	    ].join('').format(this.state == 'on' ? 0 : -37));
	    
		this.setValue( this.state );

		// click handling
		this.wrapper.click( function() {
			_this.setValue( _this.state == 'on' ? 'off' : 'on' );
		} );
	}	
	IPhoneSwitch.prototype.getValue = function(){		
		return this.wrapper.attr('selectedvalue') === 'true';
	};
	IPhoneSwitch.prototype.setValue = function(state){	
	    var _this = this;
		if( !state || state === 'off' ) {
			_this.wrapper.find('.iphone-switch').animate({ backgroundPosition: -37 }, "slow", function() {
				_this.wrapper.attr('selectedvalue', false);
			});
			_this.state = 'off';
		}
		else {
			_this.wrapper.find('.iphone-switch').animate({ backgroundPosition: 0 }, "slow", function() {
				_this.wrapper.attr('selectedvalue', true);
			});			
			_this.state = 'on';
		}
	};
	
	//-----------------------------------------------------------
	
	$.fn.iphoneSwitch = function(start_state) {
		//create the switch
		return this.each(function() {
		    var iphoneSwitchObj = new IPhoneSwitch(this, start_state);		    
			$(this).data('iphoneSwitch', iphoneSwitchObj).data('formField', iphoneSwitchObj);
		});
	};
	
	//------------------------------------------------------------

    $(function(){
        $('.iphoneSwitch').each(function(){            
            $(this).iphoneSwitch($(this).attr('defValue') || 'off');
        });
    });

})($);